package com.phone.servlet;

import com.phone.ParameterCheck;
import com.phone.entity.CashHistory;
import com.phone.entity.Result;
import com.phone.exception.ErrorCode;
import com.phone.exception.ErrorException;
import com.phone.handle.CashHandle;
import com.phone.handle.EntityHandle;
import org.hibernate.Session;
import org.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import java.util.Date;

/**
 * Created by tisen on 2017/9/8.
 * <p>
 *
 */
@WebServlet(name = "Cash", urlPatterns = "/cash")
public class CashServlet extends EntityServlet<CashHistory> {

    private static final String OWNER_ID = "owner";
    private static final String ACCOUNT = "account";
    private static final String MONEY = "money";
    private static final String TYPE = "type";
    private static final String COMPLETE = "complete";

    @Override
    protected JSONObject otherHandle(String action, ParameterCheck check, Session session) throws Exception {
        if (action.equals(COMPLETE)) {
            String id = check.getParameterString(ID, false);
            CashHandle cashHandle = new CashHandle(session);
            cashHandle.complete(id);
            Result<String> result = new Result<>();
            result.setResult(SUCCESS);
            result.setReason("complete cash success");
            return new JSONObject(result);
        } else {
            throw new ErrorException(ErrorCode.UN_DEFINED_ACTION);
        }
    }

    @Override
    public CashHistory getEntity(ParameterCheck check) throws Exception {
        CashHistory cashHistory = new CashHistory();
        cashHistory.setType(check.getParameterInt(TYPE, false, 0));
        cashHistory.setAccount(check.getParameterString(ACCOUNT, false));
        cashHistory.setMoney(check.getParameterFloat(MONEY, false, 0));
        cashHistory.setOwner(check.getParameterString(OWNER_ID, false));
        cashHistory.setDate(new Date());
        return cashHistory;
    }

    @Override
    public CashHistory getUpdateEntity(ParameterCheck check) throws Exception {
        CashHistory cashHistory = new CashHistory();
        cashHistory.setId(check.getParameterString(ID, false));
        cashHistory.setCompleteDate(new Date());
        cashHistory.setComplete(check.getParameterBoolean(COMPLETE, true, false));
        return cashHistory;
    }

    @Override
    public String getSearch(ParameterCheck check) throws Exception {
        String owner = check.getParameterString(OWNER_ID, false);
        return "from CashHistory where owner = '" + owner + "'";
    }

    @Override
    public String getOwnerID(ParameterCheck check) throws Exception {
        return check.getParameterString(OWNER_ID, false);
    }

    @Override
    public EntityHandle getHandle(Session session) {
        return new CashHandle(session);
    }
}
